package com.cxw.healthserver.utils

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
import java.security.MessageDigest


class Md5Util {

    companion object {
        /**
         * 获取
         * @param file File?
         * @return String?
         */
        fun getMd5FromFile(file: File?): String {
            if (file == null) {
                return ""
            }
            var value: String = ""
            var inputStream: FileInputStream? = null
            try {
                inputStream = FileInputStream(file)
                val byteBuffer: MappedByteBuffer = inputStream.channel.map(
                    FileChannel.MapMode.READ_ONLY, 0, file.length()
                )
                val md5: MessageDigest = MessageDigest.getInstance("MD5")
                md5.update(byteBuffer)
                value = md5.digest().joinToString("") { "%02x".format(it) }
            } catch (e: Exception) {
                System.err.println("UpdateUtil2.0 ----MD5--${"获取Md5异常"}")
                e.printStackTrace()
            } finally {
                if (null != inputStream) {
                    try {
                        inputStream.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
            System.err.println("UpdateUtil2.0 ----MD5--${value}")
            return value
        }


        fun bytesToHexString(src: ByteArray?): String? {
            val result = StringBuilder("")
            if (src?.isEmpty() == true) {
                return null
            }

            src?.forEach {
                var i = it.toInt()
                //这里需要对b与0xff做位与运算，
                //若b为负数，强制转换将高位位扩展，导致错误，
                //故需要高位清零
                val hexStr = Integer.toHexString(i and 0xff)
                //若转换后的十六进制数字只有一位，
                //则在前补"0"
                if (hexStr.length == 1) {
                    result.append(0)
                }
                result.append(hexStr)
            }
            return result.toString()
        }
    }
}
